package com.sky.task;

import com.sky.entity.Orders;
import com.sky.mapper.OrderMapper;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.time.LocalDateTime;
import java.util.List;

@Component
public class MyTask {

    @Resource
    private OrderMapper orderMapper;
    /**
     * 每分钟检查是否有超时的订单
     */
    @Scheduled(cron = "0 * * * * ?")
    public void processTimeoutOrder(){
        LocalDateTime time = LocalDateTime.now().plusMinutes(-15);
        List<Orders> orders = orderMapper.getByStatusAndOrderTimeLT(Orders.PENDING_PAYMENT, time);
        if (orders!=null&&!orders.isEmpty()){
            for (Orders order : orders) {
                order.setStatus(Orders.CANCELLED);
                order.setCancelReason("订单超时，已取消");
                order.setCancelTime(LocalDateTime.now());
                orderMapper.updateById(order);
            }
        }
    }

    /**
     * 将前一天的派送中的订单进行完成（0点之后就是第二天）
     */
    @Scheduled(cron = "0 0 1 * * ?")
    public void processDeliveryOrder(){
        //此时当前时间是1:00-60min
        LocalDateTime time = LocalDateTime.now().plusMinutes(-60);
        List<Orders> orders = orderMapper.getByStatusAndOrderTimeLT(Orders.DELIVERY_IN_PROGRESS, time);
        if (orders!=null&& !orders.isEmpty()){
            for (Orders order : orders) {
                order.setStatus(Orders.COMPLETED);
                orderMapper.updateById(order);
            }
        }
    }
}
